<template>
  <div class="search-container">
    <!-- 搜索框 -->
    <div class="search-bar">
      <div class="search-box">
        <div class="city-name" @click="$router.push('/citylist')">
          <span class="city">{{ $store.state.city }}</span>
          <span class="icon">
            <img src="@/assets/arrow/f8.png" alt="" />
          </span>
        </div>
        <div class="search">
          <input v-model="value" type="text" @input="onSearch" placeholder="请输入搜索关键字" />
        </div>
      </div>
      <div class="cancel" @click="back">取消</div>
    </div>
    <!-- 搜索历史 -->
    <div class="history" v-if="value == '' && historySearch.length > 0">
      <div class="title">搜索历史</div>
      <div class="search-list">
        <div class="search-item" v-for="s in historySearch" :key="s.id" @click="searchCurrent(s.text)">
          <span>{{ s.text }}</span>
          <span class="remove" @click.stop="removeItem(s)">
            <img src="@/assets/error/_5.png" alt="" />
          </span>
        </div>
      </div>
    </div>

    <!-- 搜索出来的数据 -->
    <van-tabs v-model="active" animated v-if="value !== ''" sticky offset-top="46px">
      <van-tab title="综合">
        <refresh-list :canFresh="true" :status="status" @on-load="onLoad">
          <template #content>
            <tags-list :tags="tags" v-if="tags.length > 0"></tags-list>
            <activity-list :activities="activityList"></activity-list>
          </template>
          <template #list>
            <div>
              <div class="title">晒图</div>
              <div class="side-list">
                <div class="side-left">
                  <search-side-item
                    v-for="(s, i) in LeftSideList"
                    :key="i"
                    :side_url="s.pics && s.pics[0].gif_url ? s.pics[0].gif_url : s.pics[0].url"
                    :title="s.title"
                    :address="s.feed && s.feed.title"
                    :head_url="s.send_user && s.send_user.avatar"
                    :nickName="s.send_user && s.send_user.name"
                    :type="s.type"
                    :count="s.like_count"
                    :id="s.id"
                  ></search-side-item>
                </div>
                <div class="side-right">
                  <search-side-item
                    v-for="(s, i) in RightSideList"
                    :key="i"
                    :side_url="s.pics && s.pics[0].gif_url ? s.pics[0].gif_url : s.pics[0].url"
                    :title="s.title"
                    :address="s.feed && s.feed.title"
                    :head_url="s.send_user && s.send_user.avatar"
                    :nickName="s.send_user && s.send_user.name"
                    :type="s.type"
                    :count="s.like_count"
                    :id="s.id"
                  ></search-side-item>
                </div>
              </div>
            </div>
          </template>
        </refresh-list>
      </van-tab>
      <van-tab title="地点">
        <refresh-list :canFresh="true" :status="status1" @on-load="onLoad">
          <template #list>
            <div class="nearby-list">
              <nearby-item v-for="(s, i) in nearbyList" :key="i" :address="s.address" :feed_url="s.cover && s.cover.url" :likes="s.collect_count" :pic_count="s.pic_count" :title="s.name" :id="s.id"></nearby-item>
            </div>
          </template>
        </refresh-list>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import axios from '@/utils/request'
import local from '@/utils/localStorage'
import TagsList from './TagsList.vue'
import ActivityList from './ActivityList.vue'
import NearbyItem from './NearbyItem.vue'
import RefreshList from '../activity/public-component/RefreshList.vue'
import SearchSideItem from './SearchSideItem.vue'
export default {
  components: {
    TagsList,
    ActivityList,
    NearbyItem,
    RefreshList,
    SearchSideItem,
    SearchSideItem
  },
  data() {
    return {
      status: {
        isLoading: false,
        finished: false,
        loading: false
      },
      status1: {
        isLoading: false,
        finished: false,
        loading: false
      },
      value: '',
      page: 1,
      nearbyPage: 1, // 地点页面page参数
      timer: null,
      nearbyList: [], // 地点数据列表
      activityList: [], // 活动列表
      LeftSideList: [], // 晒图列表
      RightSideList: [], // 晒图列表
      historySearch: [], // 历史搜索
      tags: [], // 标签列表
      active: 0
    }
  },
  methods: {
    // 请求搜索页面晒图数据
    async requestSideData() {
      /*
      请求地址：https://api.xmonster.cn/v2/posts
      请求方式：get
      请求参数：
      params:{
        city_name: 城市名称
        page： 1
        lat：31.2303904
        query： 搜索关键词
        limit： 20
        lng: 121.4737021
      }
      */
      const data = await axios.get('/v2/posts', {
        params: {
          city_name: this.$store.state.city,
          page: this.page,
          lat: this.$store.state.lat,
          lng: this.$store.state.lng,
          limit: 20,
          query: this.value
        }
      })
      if (data.length > 0) {
        data.forEach((item, index) => {
          if (index % 2 == 0) {
            this.LeftSideList.push(item)
          } else {
            this.RightSideList.push(item)
          }
        })
        this.status.isLoading = false
        this.status.Loading = false
        this.page++
      } else {
        this.status.finished = true
      }
    },
    // 请求搜索页面活动
    async requestActivityList() {
      /*
      请求地址：https://api.xmonster.cn/v2/feeds/search
      请求方式：get
      请求参数：
      params：{
        city_name: 城市名称
        page： 1
        lat：31.2303904
        query： 搜索关键词
        limit： 3
        lng: 121.4737021
      }
      */
      const data = await axios.get('/v2/feeds/search', {
        params: {
          city_name: this.$store.state.city,
          page: 1,
          lat: this.$store.state.lat,
          lng: this.$store.state.lng,
          limit: 3,
          query: this.value
        }
      })
      if (data.length > 0) {
        this.activityList = [...data]
      }
    },
    // 发送搜索请求之后请求tag标签
    async requestTag() {
      /*
      请求地址：https://api.xmonster.cn/v2/subjects
      请求方式：get
      请求参数：
      params:{
        query: 查询参数
        page：1，
        limit： 10
      }
      */
      const data = await axios.get('/v2/subjects', {
        params: {
          city_name: this.$store.state.city,
          page: this.actPage,
          limit: 10,
          lat: this.$store.state.lat,
          lng: this.$store.state.lng,
          query: this.value
        }
      })
      if (data.length > 0) {
        this.tags = [...data]
      }
    },
    // 地点页面的请求数据
    async requestNearbyList() {
      /*
      请求地址：https://api.xmonster.cn/v2/pois/search_nearby
      请求方式：get
      请求参数：
      params： {
        city_name: this.$store.state.locationCity,
          page: this.actPage,
          lat: '31.2303904',
          lng: '121.4737021',
          limit: 40,
          query: this.value
      }
      */
      const data = await axios.get('/v2/pois/search_nearby', {
        params: {
          city_name: this.$store.state.city,
          page: this.nearbyPage,
          limit: 0,
          lat: this.$store.state.lat,
          lng: this.$store.state.lng,
          query: this.value
        }
      })
      if (data.length > 0) {
        this.nearbyList = [...this.nearbyList, ...data]
        this.status1.isLoading = false
        this.status1.loading = false
        this.nearbyPage++
      } else {
        this.status1.finished = true
      }
    },
    searchCurrent(text) {
      this.value = text
      this.$store.commit('setValue', text)
      this.sendRequest()
    },
    async sendRequest() {
      const Toast = this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: '加载中...'
      })
      this.requestSideData()
      this.requestNearbyList()
      this.requestTag()
      await this.requestActivityList()
      Toast.clear()
    },
    onSearch() {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (this.value == '') {
        this.$store.commit('setValue', this.value)
        return
      }
      this.$store.commit('setValue', this.value)

      this.timer = setTimeout(() => {
        this.historySearch = []
        this.activityList = []
        // 发起请求
        this.sendRequest()
        // 像本地存储添加一次记录
        local.addData({
          id: new Date().getTime(),
          text: this.value
        })
        this.historySearch = local.getData()
      }, 500)
    },
    removeItem(item) {
      local.removeData(item)
      this.historySearch = local.getData()
    },
    // 滚动加载更多
    async onLoad() {
      if (this.value == '') {
        this.status.loading = false
        this.status1.loading = false
        return
      }
      if (this.active == 0) {
        await this.requestSideData()
        this.status.loading = false
      } else {
        await this.requestNearbyList()
        this.status1.loading = false
      }
    },
    back() {
      this.$store.commit('setValue', '')
      this.$router.back()
    }
  },
  created() {
    this.value = this.$store.state.value
    this.historySearch = local.getData()
    if (this.value !== '') {
      this.sendRequest()
    }
  }
}
</script>

<style lang="less" scoped>
.search-container {
  padding: 46px 10px 0;

  ::v-deep .van-tab {
    color: #aaa;

    &.van-tab--active {
      color: #323232;
      font-weight: 700;
    }
  }

  .search-bar {
    background-color: #d94648;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 46px;
    padding: 0 20px;
    z-index: 10;
    display: flex;
    align-items: center;

    .search-box {
      display: flex;
      align-items: center;
      background-color: #fff;
      width: 100%;
      height: 26px;
      flex: 1;

      .city-name {
        display: flex;
        align-items: center;
        font-size: 12px;
        color: #989898;
        padding: 0 5px;
        margin-right: 5px;
        font-weight: 500;
        border-right: 2px solid #989898;

        .city {
          max-width: 60px;
          white-space: nowrap;
          overflow: hidden;
        }

        .icon {
          width: 10px;
          height: 6px;
          margin-left: 2px;
          transform: translateY(-2px);
          align-self: flex-start;

          img {
            height: 100%;
            width: 100%;
          }
        }
      }

      .search {
        flex: 1;

        input {
          outline: none;
          border: none;
          font-size: 12px;
        }
      }
    }
    .cancel {
      font-size: 14px;
      color: #fff;
      padding-left: 10px;
      line-height: 30px;
    }
  }
  .history {
    padding: 10px;

    .title {
      color: #000;
      font-size: 14px;
      font-weight: 700;
      padding: 10px 0;
    }
    .search-list {
      display: flex;
      flex-wrap: wrap;

      .search-item {
        margin: 5px;
        padding: 5px 20px;
        border-radius: 999px;
        font-size: 12px;
        color: #aaa;
        position: relative;
        background-color: #f1f1f1;

        .remove {
          position: absolute;
          right: 0;
          top: 0;
          height: 10px;
          width: 10px;
          border-radius: 999px;

          img {
            height: 100%;
            width: 100%;
            overflow: hidden;
          }
        }
      }
    }
  }

  ::v-deep .van-tabs__nav--line {
    position: sticky;
    top: 46px;
    left: 0;
  }
  .nearby-list {
    padding: 10px 10px 15px;
  }

  .title {
    color: #333;
    font-size: 18px;
    font-weight: 700;
    padding: 5px 10px;
  }
  .side-list {
    display: flex;
    padding-top: 10px;

    .side-right,
    .side-left {
      width: 50%;
      padding: 5px;
    }
  }
}
</style>
